%{
/*********************************************
2112433 石长伟
中缀转后缀
YACC file
**********************************************/
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#ifndef YYSTYPE
#define YYSTYPE char*
#endif
char numstr[50];
int yylex();
extern int yyparse();
FILE* yyin;
void yyerror(const char* s);
%}

//TODO:给每个符号定义一个单词类别
%token ADD MINUS
%token MULT DIV
%token UMINUS
%token LPAR RPAR
%token NUMBER 

%left ADD MINUS
%left MULT DIV
%right UMINUS     
%left LPAR RPAR

%%


lines   :       lines expr ';' { printf("%s\n", $2); }
        |       lines ';'
        |
        ;
//TODO:完善表达式的规则
expr    :       expr ADD expr   { $$=(char*)malloc(50*sizeof(char));strcpy($$,$1);strcat($$,$3);strcat($$,"+"); }
        |       expr MINUS expr   { $$=(char*)malloc(50*sizeof(char));strcpy($$,$1);strcat($$,$3);strcat($$,"-"); }
        |       expr MULT expr  {$$=(char*)malloc(50*sizeof(char));strcpy($$,$1);strcat($$,$3);strcat($$,"*");}
        |       expr DIV expr   {$$=(char*)malloc(50*sizeof(char));strcpy($$,$1);strcat($$,$3);strcat($$,"/");}
        |       LPAR expr RPAR  {$$=(char*)malloc(50*sizeof(char));strcpy($$,$2);}
        |       MINUS expr %prec UMINUS   {$$=(char*)malloc(50*sizeof(char));strcpy($$,$2);strcat($$,"-");}
        |       NUMBER  {$$=(char*)malloc(50*sizeof(char));strcpy($$,$1);strcat($$," ");} //SPACE
        ;

%%

// programs section

int yylex()
{
    char t;
    while(1){
        t=getchar();
        if(t==' '||t=='\t'||t=='\n'){
            //do noting
        }else if(isdigit(t)){
            //TODO:解析多位数字返回数字类型 
            int i=0;
            while(isdigit(t)){
                numstr[i]=t;
                t=getchar();
                i++;
            }
            numstr[i]='\0';
            yylval=numstr;
            ungetc(t,stdin);
            return NUMBER;
        }else if(t=='+'){
            return ADD;
        }else if(t=='-'){
            return MINUS;
        }//TODO:识别其他符号
        else if(t=='*'){
            return MULT;
        }else if(t=='/'){
            return DIV;
        }else if(t=='('){
            return LPAR;
        }else if(t==')'){
            return RPAR;
        }
        else{
            return t;
        }
    }
}

int main(void)
{
    yyin=stdin;
    do{
        yyparse();
    }while(!feof(yyin));
    return 0;
}
void yyerror(const char* s){
    fprintf(stderr,"Parse error: %s\n",s);
    exit(1);
}
